package org.example.structure.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * 类描述：享元模式
 * <br>
 *
 * @author ZS
 * @version 1.0
 * @date 2020/12/30
 **/
public class FlyweightDemo {
    public static void main(String[] args) {
        Flyweight flyweight = FlyweightFactory.getFlyweight("世界");
        flyweight.operation("你好");
    }

    interface Flyweight {
        void operation(String extrinsicState);
    }

    // 具体享元角色
    static class ConcreteFlyweight implements Flyweight {
        // 内部状态，不变的对象
        private String intrinsicState;

        public ConcreteFlyweight(String intrinsicState) {
            this.intrinsicState = intrinsicState;
        }

        @Override
        public void operation(String extrinsicState) {
            System.out.println("内部不变对象："+extrinsicState);
        }
    }

    // 享元工厂
    static class FlyweightFactory {
        private static Map<String, Flyweight> pool = new HashMap<>();

        public static Flyweight getFlyweight(String intrinsicState) {
            // 由于内部状态具有不变性，所以作为缓存的键
            if (!pool.containsKey(intrinsicState)) {
                Flyweight flyweight = new ConcreteFlyweight(intrinsicState);
                pool.put(intrinsicState, flyweight);
            }
            return pool.get(intrinsicState);
        }
    }
}
